package com.zhiyizhen.handheld.component.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;

import com.zhiyizhen.handheld.R;
import com.zhiyizhen.handheld.common.Base64ImageLoader;
import com.zhiyizhen.handheld.common.ClickUtil;
import com.zhiyizhen.handheld.common.DataCache;
import com.zhiyizhen.handheld.common.LogUtil;
import com.zhiyizhen.handheld.common.MD5Util;
import com.zhiyizhen.handheld.common.RxJavaUtil;
import com.zhiyizhen.handheld.common.ToastUtil;
import com.zhiyizhen.handheld.common.sp.SpConstant;
import com.zhiyizhen.handheld.common.sp.SpUtil;
import com.zhiyizhen.handheld.common.view.BaseActivity;
import com.zhiyizhen.handheld.component.login.api.ILoginService;
import com.zhiyizhen.handheld.component.login.bean.CaptchaImageBean;
import com.zhiyizhen.handheld.component.login.bean.LoginBean;
import com.zhiyizhen.handheld.component.login.bean.LoginReq;
import com.zhiyizhen.handheld.component.main.MainActivity;
import com.zhiyizhen.handheld.component.main.api.IMainService;
import com.zhiyizhen.handheld.component.main.bean.MenuItemBean;
import com.zhiyizhen.handheld.databinding.ActivityLoginBinding;
import com.zhiyizhen.handheld.net.ResponseException;
import com.zhiyizhen.handheld.net.ServiceFactory;
import com.zhiyizhen.handheld.net.response.ResponseData;
import com.zhiyizhen.handheld.net.response.ResponseObserver;

import java.util.List;

public class LoginActivity extends BaseActivity {
    private ActivityLoginBinding binding;
    private String uuid;
    private String image;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        boolean isChecked = SpUtil.getBoolean(SpConstant.REMEMBER_PASSWORD, false);
        binding.rememberPasswordCb.setChecked(isChecked);
        if (isChecked) {
            binding.passwordTv.setText(SpUtil.getString(SpConstant.PASSWORD, ""));
        }
        binding.userNameTv.setText(SpUtil.getString(SpConstant.MOBILE, ""));

        binding.loginBtn.setOnClickListener(v -> {
            if (!ClickUtil.isValid()) {
                return;
            }
            SpUtil.putString(SpConstant.MOBILE, binding.userNameTv.getText().toString());
            if (binding.rememberPasswordCb.isChecked()) {
                SpUtil.putString(SpConstant.PASSWORD, binding.passwordTv.getText().toString());
            }
            SpUtil.putBoolean(SpConstant.REMEMBER_PASSWORD, binding.rememberPasswordCb.isChecked());

            login();
        });

        binding.captchaImage.setOnClickListener(v -> requestCaptchaImage());

        requestCaptchaImage();
    }

    private void login() {
        String userName = binding.userNameTv.getText().toString();
        String password = binding.passwordTv.getText().toString();
        String code = binding.captchaImageResult.getText().toString();
        if (TextUtils.isEmpty(userName)) {
            binding.phoneNumberErrorTv.setVisibility(View.VISIBLE);
            ToastUtil.showShort(R.string.pls_input_account);
            return;
        }

        if (userName.length() != 11) {
            binding.phoneNumberErrorTv.setVisibility(View.VISIBLE);
            return;
        }
        binding.phoneNumberErrorTv.setVisibility(View.INVISIBLE);
        if (TextUtils.isEmpty(password)) {
            ToastUtil.showShort(R.string.pls_input_password);
            return;
        }

        if (TextUtils.isEmpty(code)) {
            ToastUtil.showShort(R.string.pls_input_captcha);
            return;
        }
        LoginReq req = new LoginReq(userName, MD5Util.md5MessageDigest(password));
        req.setUuid(uuid);
        req.setCode(code);

        ServiceFactory.getService(ILoginService.class)
                .login(req)
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {

                    @Override
                    protected void onSuccess(ResponseData<LoginBean> responseData) {
                        DataCache.setLoginBean(responseData.getData());

                        DataCache.requestEnumsMap(() -> {
                            getMenuList(responseData.getData());
                        });
                    }

                    @Override
                    protected void onFailure(ResponseException e) {
                        super.onFailure(e);
                        requestCaptchaImage();
                    }
                });
    }

    private void requestCaptchaImage() {
        ServiceFactory.getService(ILoginService.class)
                .requestCaptchaImage()
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {

                    @Override
                    protected void onSuccess(ResponseData<CaptchaImageBean> responseData) {
                        if (responseData != null && responseData.getData() != null) {
                            LogUtil.d("responseData---" + responseData.getData().getUuid());
                            uuid = responseData.getData().getUuid();
                            image = responseData.getData().getImg();
                            Base64ImageLoader.loadBase64Image(image, binding.captchaImage);
                        }
                    }
                });
    }

    private void getMenuList(LoginBean loginBean) {
        if (loginBean == null) {
            return;
        }
        ServiceFactory.getService(IMainService.class)
                .getMenuList(loginBean.getToken(), loginBean.getClinicId())
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    @Override
                    protected void onSuccess(ResponseData<List<MenuItemBean>> responseData) {
                        if (responseData != null) {
                            DataCache.setMenuList(responseData.getData());
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            finish();
                        }
                    }
                });
    }

    public static void start(Context context) {
        Intent starter = new Intent(context, LoginActivity.class);
        context.startActivity(starter);
    }

}
